<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>海报贴图</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>八年合伙人海报贴图</h1>

<div class="container">
  <form id="myForm" enctype="multipart/form-data">
    <div class="form-group">
      <label for="type">海报类型：</label>
      <select id="type" name="type" onchange="showImage(this)">
        <option value="" selected>请选择</option>
      </select>
    </div>
    <br/>
    <div id="poster" style="width: 100%; height: 200px; overflow: hidden;">
      <img id="posterPreview" src="#" alt="海报预览" style="width: 100%; height: 100%; object-fit: contain;">
    </div>

    <div class="col-lg-12 col-md-12 col-sm-12">
      <label for="file">选择贴图：</label>
      <input type="file" id="file" name="file" onchange="showPreviewSelected(this)"/>
      <br/>
      <div id="watermark" style="width: 100%; height: 100px; overflow: hidden;">
        <img id="watermarkPreview" src="#" alt="贴图预览" style="width: 100%; height: 100%; object-fit: contain;">
      </div>
    </div>

    <button type="button" id="submitBtn">生成图片</button>
  </form>

  <div class="col-lg-12 col-md-12 col-sm-12">
    <h2>图片预览</h2>
    <br/>
    <div id="image" style="width: 100%; height: 200px; overflow: hidden;">
      <img id="imagePreview" src="#" style="width: 100%; height: 100%; object-fit: contain;">
    </div>
  </div>
</div>

<script>
  fetch('/poster/init')
    .then(response => response.json())
    .then(data => {
      const type = document.getElementById('type');
      data.forEach(item => {
        const option = document.createElement('option');
        option.value = item.type;
        option.text = item.name;
        option.dataset.sourceImg = item.sourceImg;
        type.appendChild(option);
      });
    })
    .catch(error => console.error(error));

  function showImage(select) {
    var selectedOption = select.options[select.selectedIndex];
    document.getElementById('posterPreview').src = selectedOption.dataset.sourceImg;
  }

  function showPreviewSelected(input) {
    if (input.files && input.files[0]) {
      var reader = new FileReader();
      reader.onload = function (e) {
        document.getElementById('watermarkPreview').src = e.target.result;
      }
      reader.readAsDataURL(input.files[0]);
    }
  }

  $('#submitBtn').click(function () {
    var formData = new FormData();
    formData.append('file', $('#file')[0].files[0]);
    formData.append('type', $("#type").val());

    $.ajax({
      url: '/poster/upload',
      type: 'POST',
      data: formData,
      processData: false,
      contentType: false,
      success: function (data) {
        document.getElementById('imagePreview').src = "data:image/png;base64," + data;
      },
      error: function () {
        $('#result').text('文件上传失败');
      }
    });
  });
</script>

</body>
</html>